package com.mayikt.main.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@WebFilter
@Slf4j
public class SignFilter implements Filter {
    /**
     * 排除其他请求-+--白名单
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 拦截请求,验证json数据 签名
        RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);
        String json = requestWrapper.getBody();
        // 验证token
        HttpServletRequest req = (HttpServletRequest) request;
        String sign = req.getHeader("sign");
        String timestamp = req.getHeader("timestamp");
        boolean result = SignUtil.verifyJson(json, sign, timestamp);
        if (!result) {
            PrintWriter writer = response.getWriter();
            writer.println("fail");
            writer.close();
            return;
        }
        // 验证签名 放行请求
        chain.doFilter(requestWrapper, response);
    }


    @Override
    public void destroy() {

    }
}

